package serial.utils;

import android.app.Activity;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidParameterException;

import serial.utils.SerialPort;

public class SerialZbThread extends Thread {
    IZgibeeRec iZgibeeRec; //接口类
    Activity activity;

    public IZgibeeRec getiZgibeeRec() {
        return iZgibeeRec;
    }

    public void setiZgibeeRec(IZgibeeRec iZgibeeRec) {
        this.iZgibeeRec = iZgibeeRec;
    }

    boolean isRuning = false; //是否在运行

    //"/dev/ttyAMA4"
    public SerialZbThread(String path) {
        try {
            OpenPort(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public synchronized void start() {
        isRuning = true;
        super.start();
    }

    @Override
    public void interrupt() {
        isRuning = false;
        try {
            this.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        closeSerialPort();
        super.interrupt();
    }

    //关闭输入输出流关闭串口
    private void closeSerialPort() {
        if (mInputStream != null) {
            try {
                mInputStream.close();
                mInputStream = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mOutputStream != null) {
            try {
                mOutputStream.close();
                mOutputStream = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (mSerialPort != null) {
            mSerialPort.close();
            mSerialPort = null;
        }
    }

    @Override
    public void run() {
        super.run();
        while (isRuning) {
            try {
                Thread.sleep(100);
                int num = mInputStream.available();
                byte[] buff = new byte[num];
                int ret = 0;
                ret = mInputStream.read(buff);
                if (ret > 1) {
//                    int len = (buff[1] & 0xFF) + 6;
//                    System.out.println("数据长度：" + len + "  接收的数据长度：" + ret);
                    comDataHandler(buff, ret);
                }
            } catch (Exception e) {
                resetComDataHandler();
                Log.d("error", "error com");
                //continue;
                e.printStackTrace();
                //return;
            }
        }
    }

    private SerialPort mSerialPort = null; //串口类
    private InputStream mInputStream = null; //输入流
    private OutputStream mOutputStream = null; //输出流

    final static int IOCTRL_PMU_RFID_ON = 0x03;
    final static int IOCTRL_PMU_RFID_OFF = 0x04;

    final static int IOCTRL_PMU_BARCODE_ON = 0x05;
    final static int IOCTRL_PMU_BARCODE_OFF = 0x06;
    final static int IOCTRL_PMU_BARCODE_TRIG_LOW = 0x12;

    //打开串口
    private void OpenPort(String path) throws SecurityException, IOException {
        if (mSerialPort == null) {
//            String path = "/dev/ttyAMA4";   //串口号

            int baudrate = Integer.decode("38400"); //波特率
            int nbits = Integer.decode("8");  //数据位
            int nstop = Integer.decode("1"); //停止位

            String sVerify = "N";
            char cVerify = sVerify.charAt(0);

            /* Check parameters */
            if ((path.length() == 0) || (baudrate == -1) || nbits == -1 || nstop == -1 || cVerify == 'C') {
                Log.d("11111111", "yyyyyyyyyyyyyy");
                throw new InvalidParameterException();
            }
            Log.d("11111111", "111111111111111111111111111111111");
            /* Open the serial port */
            mSerialPort = new SerialPort(new File(path), baudrate, nbits, cVerify, nstop, 0);
            Log.d("11111111", "2222222222222222222222222222222222");
            mOutputStream = mSerialPort.getOutputStream();
            mInputStream = mSerialPort.getInputStream();
            mSerialPort.sri_Init();
            mSerialPort.sri_IOCTL(IOCTRL_PMU_BARCODE_TRIG_LOW);
            mSerialPort.sri_IOCTL(IOCTRL_PMU_BARCODE_ON);
            mSerialPort.sri_IOCTL(IOCTRL_PMU_RFID_ON);
            Log.d("11111111", "333333333333333333333333333333333");
        } else {
            //view1.setText("串口已打开");
            System.out.println("串口已打开");
        }
    }

    //给传感器发送命令
    public void sendZigBee(byte[] zigbeeInfo) {
        try {
            mOutputStream.write(zigbeeInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //防止串口数据丢包
    byte[] totalPacket = null;
    int byteLeft = 0;
    int packetLen = 0;
    boolean isPloay = false;

    public void resetComDataHandler() {
        totalPacket = null;
        byteLeft = 0;
        packetLen = 0;
        isPloay = false;
    }

    //数据防丢包方法
    private void comDataHandler(byte[] buffer, int len) {
//        System.out.println("len:" + len);
//        System.out.println("buffer:" + bytesToHexString(buffer));
        if (len > 1) {
            if (byteLeft == 0) {  //
                if (buffer[0] == (byte) 0xFA || buffer[0] == (byte) 0xFD) {
                    packetLen = (buffer[1] & 0xFF) + 6;
                    totalPacket = new byte[packetLen];
//                    System.out.println("packetLen:" + packetLen);
                    if (len < packetLen) {
                        System.arraycopy(buffer, 0, totalPacket, byteLeft, len);
                        byteLeft += len;
                    } else {
                        packetLen = (buffer[1] & 0xFF) + 6;
                        int srcPos = 0;
                        while (packetLen <= len) {
                            System.arraycopy(buffer, srcPos, totalPacket, byteLeft, packetLen); //0
//                            System.out.println("totalPacket:" + bytesToHexString(totalPacket));
                            if (iZgibeeRec != null)
                                iZgibeeRec.onRecDataCom(totalPacket, packetLen);
//                            if (iProcessMain != null)
//                                iProcessMain.onRecComData(totalPacket, packetLen);
                            srcPos += packetLen;
                            len -= packetLen;
                            if (len > 1) {
                                packetLen = (buffer[srcPos + 1] & 0xFF) + 6;
                                totalPacket = new byte[packetLen];

                            }
//                            System.out.println("srcPos:" + srcPos);
//                            System.out.println("totalPacketlen:" + packetLen);
                        }
                        byteLeft += len;
                        if (byteLeft > 0) {
                            System.arraycopy(buffer, srcPos, totalPacket, 0, byteLeft);
                        }
                    }

                }
            } else if (byteLeft > 0) {
//                System.out.println("byteleft:" + byteLeft);
                if (len <= packetLen - byteLeft) {
                    System.arraycopy(buffer, 0, totalPacket, byteLeft, len);
                    byteLeft += len;
                    if (byteLeft == packetLen)
                        isPloay = true;
                } else {
                    int byteRight = packetLen - byteLeft;
//                    System.out.println("byteRight:" + byteRight);
                    System.arraycopy(buffer, 0, totalPacket, byteLeft, byteRight);
                    if (iZgibeeRec != null)
                        iZgibeeRec.onRecDataCom(totalPacket, packetLen);
//                    if (iProcessMain != null)
//                        iProcessMain.onRecComData(totalPacket, packetLen);

                    packetLen = (buffer[byteRight + 1] & 0xFF) + 6;
                    totalPacket = new byte[packetLen];
                    byteLeft = 0;
                    int srcPos = 0;
                    int length = len - byteRight;
                    while (packetLen <= length) {
                        System.arraycopy(buffer, srcPos, totalPacket, byteLeft, packetLen); //0
//                        System.out.println("totalPacket:" + bytesToHexString(totalPacket));
                        if (iZgibeeRec != null)
                            iZgibeeRec.onRecDataCom(totalPacket, packetLen);
//                        if (iProcessMain != null)
//                            iProcessMain.onRecComData(totalPacket, packetLen);
                        srcPos += packetLen;
                        length -= packetLen;
                        if (length > 1) {
                            packetLen = (buffer[srcPos + 1] & 0xFF) + 6;
                            totalPacket = new byte[packetLen];

                        }
//                        System.out.println("srcPos:" + srcPos);
//                        System.out.println("totalPacketlen:" + packetLen);
                    }
                    byteLeft += length;
                    if (byteLeft > 0) {
                        System.arraycopy(buffer, srcPos, totalPacket, 0, byteLeft);
                    }
                }
            }
            if (isPloay) {
                if (iZgibeeRec != null)
                    iZgibeeRec.onRecDataCom(totalPacket, packetLen);

                resetComDataHandler();
            }
        }
    }

    //串口接口
    public interface IZgibeeRec {
        /**
         * onRecDataCom
         * @param buffer 串口接收数据
         * @param len 串口接收长度
         */
        void onRecDataCom(byte[] buffer, int len);
    }

}
